package com.mr.productclient.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Class: CookieUtil
 * User (作者):MRui
 * TODO (描述)：Cookie工具类
 * Date 2018.10.03 23:28
 */
public class CookieUtil {

    /**
    * User (作者): MRui
    * TODO (描述)：设置cookie
    * Data：2018.10.03 23:32
    */
    public static void set(HttpServletResponse response,
                           String name,
                           String value,
                           int maxAge){
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    /**
    * User (作者): MRui
    * TODO (描述)：获取cookie
    * Data：2018.10.04 12:54
    */
    public static Cookie get(HttpServletRequest request,
                             String name){
        Map<String, Cookie> cookieMap = readCookieMap(request);
        //如果包含就删掉
        if (cookieMap.containsKey(name)){
            return cookieMap.get(name);
        }else {
            return null;
        }

    }

    /**
    * User (作者): MRui
    * TODO (描述)：获取cookieMap
    * Data：2018.10.04 12:58
    */
    private static Map<String, Cookie> readCookieMap(HttpServletRequest request){
        Map<String, Cookie> cookieMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies){
                cookieMap.put(cookie.getName(),cookie);
            }
        }
        return cookieMap;
    }
}
